<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\models\Tag;
use application\system\Permalink as SystemPermalink;

class Tags extends DataType {
	public static $name = 'Tags';
	public static $fields = array();
	
	public static $displayParams = array(
		array(
			'label'=>'Display As',
			'name'=>'display',
			'type'=>'select',
			'defaultValue'=>'title',
			'options'=>array(
				array(
					'label'=>'Tag Name',
					'value'=>'title'
				),
				array(
					'label'=>'Tag ID',
					'value'=>'id'
				)
			)
		),
		array(
			'label'=>'Format',
			'name'=>'format',
			'type'=>'select',
			'defaultValue'=>'ul',
			'options'=>array(
				array(
					'label'=>'Unordered List',
					'value'=>'ul'
				),
				array(
					'label'=>'Comma-Separated Values',
					'value'=>'csv'
				)
			)
		),
		array(
			'label'=>'Link',
			'name'=>'link',
			'type'=>'checkbox',
			'options'=>array(
				array(
					'label'=>'Link',
					'value'=>'TRUE',
					'name'=>'link'
				)	
			)
		)
		
	);
	
	public static function validate($field, $data, $results) {
		$group = getFieldMetaData($field->cf_id, 'group');
		if($field->cf_required && !$data['tags_'.$field->cf_id]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		else {
			$results['db_fields']['tags'][$group] = $data['tags_'.$field->cf_id];
		}
		
		return $results;
	}
	
	public static function formHeader($field) {
		Modulator()->includeScript('jquery');
		Modulator()->includeScript(getCommonFile('concerto/javascript/tags.js'));
		?>
		<script type="text/javascript">
			$(document).ready(function() {
				$('.tag-select').tags();
			});
		</script>
		<?php
	}
	
	public static function display($formElements) {
		if($formElements['elements']['element']) :
			?>
			
			<fieldset class="tags-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php
			echo $formElelements['elements']['search'];
			echo $formElements['elements']['element'];?>
			</section>
			</fieldset>
		<?php endif;
	}
	
	public static function build($field, $data) {
		// Get field meta data
		$tagGroup = getFieldMetaData($field->cf_id, 'group');
		$contentType = DB()->getVar("SELECT `tag_content_type` FROM `cn_tags` WHERE `tag_id`='$tagGroup'");
		// Get default order for the group
		$order = DB()->getVar("SELECT `tag_order` FROM `cn_tags` WHERE `tag_id`='$tagGroup'");
		switch($order) {
			case 'name':
			default:
				$orderBy = 'ORDER BY `tag_title`';
				break;
			case 'custom':
				$orderBy = 'ORDER BY `tag_order`';
				break;
		}
		// Get preexisting tags
		$contentId = $data['content_id'];
		

		
		/** Display tags */
		$formElements = array('column'=>'tags', 'display'=>$field->cf_display_name, 'data_type'=>'Tags', 'elements'=>array());
	
		
		$existingTags = $data['tags_'.$field->cf_id.''];
		
		if(!$existingTags) $existingTags = array();
		// Get available tags
		
		$attachableTags = DB()->getResults("SELECT * FROM `cn_tags` WHERE `tag_type`='tag' AND `tag_group`='$tagGroup' ".$orderBy);
		$tagSelect = '<select data-content-type="'.$contentType.'" data-tag-group="'.$tagGroup.'" multiple="multiple" class="tag-select" name="tags_'.$field->cf_id.'[]" id="tags_'.$field->cf_id.'">';
		
		foreach($attachableTags as $tag) {
			if(in_array($tag->tag_id, $existingTags)) 
				$tagSelect .= '<option selected="selected" value="'.$tag->tag_id.'">'.$tag->tag_title.'</option>';
			else
				$tagSelect .= '<option value="'.$tag->tag_id.'">'.$tag->tag_title.'</option>';
		}
		
		$tagSelect .= '</select>';
		$formElements['elements']['element'] = $tagSelect;
		
		
		return $formElements;
	
	}
	
	public static function save() {
		$field = $_REQUEST['field'];
		$group = $_REQUEST['meta_group'];
		$count = DB()->getCount("SELECT * FROM `cn_field_meta` WHERE `cfm_key`='group' AND `cfm_field`='$field'");
		if(!$count) {
			$insert = array('cfm_key'=>'group', 'cfm_value'=>$group, 'cfm_field'=>$field);
			DB()->insert('cn_field_meta', $insert);
		}
		else {	
			DB()->query("UPDATE `cn_field_meta` SET `cfm_value`='$group' WHERE `cfm_key`='group' AND `cfm_field`='$field'");
		}
	}
	
	public static function endForm($field, $data, $id, $type) {
		$group = getFieldMetaData($field->cf_id, 'group');
		$tags = $data['tags'][$group];
		if(!$tags) $tags = array();
		
		
		
		$existing = DB()->getResults("SELECT * FROM `cn_content_tag_relations` INNER JOIN `cn_content` ON `content_id`=`ctr_content` INNER JOIN `cn_tags` ON `tag_id`=`ctr_tag` WHERE `tag_group`='$group' AND `content_id`='$id'");
		
		$currentTags = array();
		foreach($existing as $tag) {
			$currentTags[$tag->ctr_id] = $tag->tag_id;
		}
		
		// Get tags that we don't have to add
		$noNeed = array_intersect($tags, $currentTags);
		
		// Get tags we need to remove
		$toDelete = array_keys(array_diff($currentTags, $noNeed));
		$toDelete = "'".implode("', '", $toDelete)."'";
		
		// Get tags we need to add
		$toAdd = array_diff($tags, $currentTags);
		

		
		DB()->query("DELETE FROM `cn_content_tag_relations` WHERE `ctr_id` IN ($toDelete) AND `ctr_content`='$id'");
		foreach($toAdd as $add) {
			DB()->insert('cn_content_tag_relations', array('ctr_content'=>$id, 'ctr_tag'=>$add));
		}
	}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		$contentId = $data['content_id'];
		$group = getFieldMetaData($field->cf_id, 'group');
		$existingTags = DB()->getVarArray("SELECT `tag_id` FROM `cn_content_tag_relations` INNER JOIN `cn_content` ON `content_id`=`ctr_content` INNER JOIN `cn_tags` ON `tag_id`=`ctr_tag` WHERE `tag_group`='$group' AND `content_id`='$contentId'");
	

		return array('tags_'.$field->cf_id => $existingTags);
	}
	
	public static function editForm($field) {
		?>
			<input type="hidden" name="field_id" value="<?=$field->getId()?>"/>
			<ul class="form-fields">
			<li>
			<label>Field Display Name</label>
			<input type="text" name="field_display_name" class="big wide" value="<?=$field->getDisplayName()?>"/>
			</li>
			<li>
			<label>Field Description</label>
			<textarea name="field_description" class="wide"><?=$field->getDescription()?></textarea>
			</li>
			<li>
				<label>Tag Group</label>
				<select name="meta_group">
					<?php $groups = DB()->getResults("SELECT * FROM `cn_tags` WHERE `tag_content_type`='".$field->getContentType()."' AND `tag_type` = 'group'");
					foreach($groups as $group) : ?>
					<option <?= ($field->getMeta('group') == $group->tag_id) ? 'selected="selected"' : ''?> value="<?=$group->tag_id?>"><?=$group->tag_title?></option>
					<?php endforeach;?>
				</select>
			</li>
			</ul>
			<?php
	}	
	
	public static function prepareData($field, $data, $params) {
		$tags = $data['tags_'.$field->cf_id];
		
		if(strtolower($params['display']) == 'title') {
			foreach($tags as $key=>$tag) {
				$tagTitle = DB()->getVar("SELECT `tag_title` FROM `tags` WHERE `tag_id`='$tag'");
				if($params['link']) {
					$link = Permalink::buildTagPermalink($tag);
					$tags[$key] = '<a href="'.$link.'">'.$tagTitle.'</a>';
				}
				else {
					$tags[$key] = $tagTitle;
				}	
					
			}
		}
		elseif($params['link']) {
			foreach($tags as $key=>$tag) {
				$link = SystemPermalink::buildTagPermalink($tag);
				$tags[$key] = '<a href="'.$link.'">'.$tagTitle.'</a>';
			}
		}
		
		switch($params['format']) {
			case 'ul':
			default:
				$return = '<ul>';
				foreach($tags as $tag) {
					$return .= '<li>'.$tag.'</li>';
				}
				$return .= '</ul>';
				break;
			case 'csv':
				$return = implode(', ', $tags);
				break;
			case 'array':
				$return = $tags;
				break;
		}
		
		return $return;
	}
	
}
?>